package com.netease.nie.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.netease.nie.base.cache.redis.Redis;
import com.netease.nie.base.utils.PageUtils;
import com.netease.nie.common.CommonService;
import com.netease.nie.constants.CachePrefixConstants;
import com.netease.nie.dao.DrawLotteryActivityDao;
import com.netease.nie.model.DrawLotteryActivity;

/**
 * 抽奖活动管理服务接口实现
 * @author gzlibingjie
 */
@Service
public class DrawLotteryActivityServiceImpl extends CommonService implements DrawLotteryActivityService {
	
	@Resource
	private DrawLotteryActivityDao drawLotteryActivityDao;
	
	@Autowired
	private Redis redis;
	
	private static final String DRAW_LOTTERY_ACTIVITY_LIST = CachePrefixConstants.DrawLotteryPrefix.DRAW_LOTTERY_ACTIVITY_LIST;
	
	private static final String DRAW_LOTTERY_ACTIVITY_PREFIX = CachePrefixConstants.DrawLotteryPrefix.DRAW_LOTTERY_ACTIVITY_PREFIX;
	
	/**
	 * 获取抽奖活动列表
	 * @param pageIndex 当前页码
	 * @return 抽奖活动列表
	 */
	@Override
	public List<DrawLotteryActivity> list(Integer pageIndex) {
		int pageStartIndex = PageUtils.getPageStartIndex(pageIndex);
		int pageEndIndex = PageUtils.getPageEndIndex(pageIndex);
		List<DrawLotteryActivity> drawLotteryActivityList = null;
		if (redis.exists(DRAW_LOTTERY_ACTIVITY_LIST)) {
			drawLotteryActivityList = redis.lrange(DRAW_LOTTERY_ACTIVITY_LIST, pageStartIndex, pageEndIndex, DrawLotteryActivity.class);
		} else {
			drawLotteryActivityList = drawLotteryActivityDao.queryAll();
			if (drawLotteryActivityList != null && !drawLotteryActivityList.isEmpty()) {
				redis.rpush(DRAW_LOTTERY_ACTIVITY_LIST, drawLotteryActivityList);
			}
			drawLotteryActivityList = PageUtils.getPageListByIndex(drawLotteryActivityList, pageStartIndex, pageEndIndex);
		}
		return drawLotteryActivityList;
	}

	/**
	 * 根据id获取抽奖活动信息
	 * @param id 抽奖活动的唯一ID
	 * @return 抽奖活动对象
	 */
	@Override
	public DrawLotteryActivity queryById(Integer id) {
		if (id == null) {
			return null;
		}
		String key = DRAW_LOTTERY_ACTIVITY_PREFIX + id;
		DrawLotteryActivity drawLotteryActivity = null;
		if (redis.exists(key)) {
			drawLotteryActivity = redis.get(key, DrawLotteryActivity.class);
		} else {
			drawLotteryActivity = drawLotteryActivityDao.queryById(id);
			if (drawLotteryActivity != null) {
				redis.set(key, drawLotteryActivity);
			}
		}
		return drawLotteryActivity;
	}

	/**
	 * 增加参与人次
	 * @param id 抽奖活动的唯一ID
	 * @return 影响的行数
	 */
	@Override
	public int addDrawUserPt(Integer id) {
		return drawLotteryActivityDao.addDrawUserPt(id);
	}

	/**
	 * 增加中奖次数
	 * @param id 抽奖活动的唯一ID
	 * @return 影响的行数
	 */
	@Override
	public int addPrizeTimes(Integer id) {
		return drawLotteryActivityDao.addPrizeTimes(id);
	}

}
